<template>
  <el-dialog :title="title[type]" :visible.sync="dialogVisible" width="80%">
    <el-form
      class="handleform"
      :disabled="disabled"
      ref="handleform"
      label-position="left"
      :rules="rules"
      :model="data"
      size="small"
      label-width="80px"
    >
      <el-row :gutter="40">
        <el-col :span="6">
          <el-form-item label="领用人" prop="applyUserId">
            <user-select
              v-model="data.applyUserId"
              :disabledId="data.returnUserId"
              :disabled="type != 'add'"
            ></user-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="领用时间" prop="applyTime">
            <el-date-picker
              v-model="applyTime"
              type="datetime"
              :disabled="type != 'add'"
              :picker-options="{
                disabledDate: (date) => {
                  if (returnTime) {
                    return date > returnTime;
                  }
                  return false;
                },
              }"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="归还人"
            :required="type == 'return'"
            prop="returnUserId"
          >
            <user-select
              v-model="data.returnUserId"
              :disabledId="data.applyUserId"
            ></user-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="归还时间"
            prop="returnTime"
            :required="type == 'return'"
          >
            <el-date-picker
              v-model="returnTime"
              type="datetime"
              :picker-options="{
                disabledDate: (date) => {
                  if (applyTime) {
                    return date < applyTime;
                  }
                  return false;
                },
              }"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="6" v-if="type != 'add'">
          <el-form-item label="库管名称">
            <el-input
              v-model="data.managementUserName"
              disabled
              style="width: 75%"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="type != 'add'">
          <el-form-item label="归还状态">
            <el-tag
              :type="returnState[data.returnState].type"
              style="margin-right: 20px"
              >{{ returnState[data.returnState].name }}</el-tag
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      v-if="type != 'add'"
      :data="data.instrument"
      ref="table"
      @selection-change="selectionChange"
    >
      <el-table-column v-if="type == 'return'" type="selection" width="55">
      </el-table-column>
      <el-table-column label="设备名称" align="center" prop="equipmentName" />
      <el-table-column label="设备编号" align="center" prop="equipmentNumber" />
      <el-table-column
        label="设备类型编号"
        align="center"
        prop="equipmentTypeNumber"
      />
      <el-table-column label="归还状态" align="center" prop="return">
        <template slot-scope="{ row }">
          <el-tag :type="row.return ? 'success' : 'warning'"
            >{{ row.return ? "已" : "未" }}归还</el-tag
          >
        </template>
      </el-table-column>
    </el-table>

    <equipment-com
      v-if="type == 'add'"
      height="400"
      @change="data.instrumentList = $event"
    ></equipment-com>
    <template slot="footer" class="dialog-footer">
      <el-button @click="request(type)" v-show="type == 'add'" type="primary"
        >添加</el-button
      >
      <el-button
        @click="request(type)"
        v-show="type == 'return'"
        type="primary"
        style="margin-right: 80px"
        >归还</el-button
      >
      <el-button @click="close">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { computed } from "vue";
import instrumentSelect from "@/components/select/src/instrumentSelect";
import { addApply, info, giveBack } from "@/api/resourse/giveBack";
import equipmentCom from "./equipment";
export default {
  name: "giveBackDialog",
  components: { instrumentSelect, equipmentCom },
  data() {
    return {
      id: null,
      title: {
        add: "添加",
        view: "详情",
        return: "归还",
      },
      data: {
        returnState: 0,
      },
      returnState: [
        {
          name: "未归还",
          type: "warning",
        },
        {
          name: "部分归还",
          type: "",
        },
        {
          name: "已归还",
          type: "success",
        },
      ],
      dataCache: {
        applyTime: null,
        returnTime: null,
        applyUserId: null,
        returnState: 0,
        instrumentList: [],
      },
      type: "return",
      dialogVisible: false,
      rules: {
        applyUserId: [{ required: true, message: "领用人不能为空" }],
        applyTime: [{ required: true, message: "领用时间不能为空" }],
        returnUserId: [
          {
            validator: (rule, value, callback) => {
              if (this.type !== "return") callback();
              if (this.data?.returnUserId) {
                callback();
              } else {
                callback(new Error("归还人不能为空"));
              }
            },
          },
        ],
        returnTime: [
          {
            validator: (rule, value, callback) => {
              if (this.type !== "return") callback();
              if (this.data?.returnTime) {
                callback();
              } else {
                callback(new Error("归还时间不能为空"));
              }
            },
          },
        ],
      },
    };
  },
  computed: {
    disabled() {
      return this.type == "view";
    },
    applyTime: {
      get() {
        return this.data.applyTime ? new Date(this.data.applyTime) : null;
      },
      set(value) {
        this.data.applyTime = this.parseTime(value);
      },
    },
    returnTime: {
      get() {
        return this.data.returnTime ? new Date(this.data.returnTime) : null;
      },
      set(value) {
        this.data.returnTime = this.parseTime(value);
      },
    },
  },
  methods: {
    selectionChange(val) {
      this.data.instrumentList.forEach((t) => {
        t.return = val.find((l) => l.equipmentId == t.equipmentId)
          ? true
          : false;
      });
    },
    request(type) {
      this.$refs.handleform.validate((valid) => {
        if (valid) {
          if (
            !this.data.instrumentList ||
            this.data.instrumentList.length == 0
          ) {
            this.$message({
              type: "warning",
              message: "仪器信息不能为空",
            });
            return;
          }
          let req = type == "add" ? addApply(this.data) : giveBack(this.data);
          req.then((res) => {
            this.$message({
              type: "success",
              message: `${type == "add" ? "添加" : "归还"}成功`,
            });
            this.close();
          });
        }
      });
    },
    open(id, type) {
      this.$set(this, "type", type);
      this.reset();
      if (id) {
        this.id = id;
        this.getData(id);
      }
      this.dialogVisible = true;
    },
    getData(id) {
      info(id).then((res) => {
        res.data.instrument = this.jsonParse(res.data.instrument);
        if (this.type == "return") {
          res.data.instrumentList = JSON.parse(
            JSON.stringify(res.data.instrument)
          );
          res.data.returnTime
            ? null
            : (res.data.returnTime = this.parseTime(new Date()));
          this.$nextTick(() => {
            setTimeout(() => {
              res.data.instrument.forEach((t) => {
                t.return && this.$refs.table.toggleRowSelection(t, t.return);
              }),
                50;
            });
          });
        }
        this.data = res.data;
      });
    },
    reset() {
      this.$nextTick(() => {
        this.$refs.handleform.resetFields();
      });
      this.data = JSON.parse(JSON.stringify(this.dataCache));
      this.type == "add"
        ? (this.data.applyTime = this.parseTime(new Date()))
        : null;
    },
    close() {
      this.dialogVisible = false;
      this.$emit("close");
    },
  },
};
</script>

<style>
.el-dialog {
  overflow: hidden;
}
</style>
